package com.patentbackend.patentmanage.service.lmpl;

import com.patentbackend.patentmanage.dto.LegalDocumentDTO;
import com.patentbackend.patentmanage.entity.LegalDocument;
import com.patentbackend.patentmanage.repository.LegalDocumentRepository;
import com.patentbackend.patentmanage.service.LegalDocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Optional;
import java.util.UUID;

@Service
public class LegalDocumentServiceImpl implements LegalDocumentService {

    @Autowired
    private LegalDocumentRepository legalDocumentRepository;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Override
    public LegalDocument create(LegalDocumentDTO documentDTO) {
        LegalDocument document = LegalDocument.builder()
                .title(documentDTO.getTitle())
                .category(documentDTO.getCategory())
                .content(documentDTO.getContent())
                .creatorId(documentDTO.getCreatorId())
                .build();

        return legalDocumentRepository.save(document);
    }

    @Override
    public LegalDocument update(Long id, LegalDocumentDTO documentDTO) {
        LegalDocument document = legalDocumentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Legal document not found with id: " + id));

        if (documentDTO.getTitle() != null) document.setTitle(documentDTO.getTitle());
        if (documentDTO.getCategory() != null) document.setCategory(documentDTO.getCategory());
        if (documentDTO.getContent() != null) document.setContent(documentDTO.getContent());

        return legalDocumentRepository.save(document);
    }

    @Override
    public boolean existsById(Long id) {
        return legalDocumentRepository.existsById(id);
    }

    @Override
    public Page<LegalDocument> findAll(Pageable pageable) {
        return legalDocumentRepository.findAll(pageable);
    }

    @Override
    public Optional<LegalDocument> findById(Long id) {
        return legalDocumentRepository.findById(id);
    }

    @Override
    public void delete(Long id) {
        legalDocumentRepository.deleteById(id);
    }

    @Override
    public String uploadFile(Long documentId, MultipartFile file) throws IOException {
        LegalDocument document = legalDocumentRepository.findById(documentId)
                .orElseThrow(() -> new RuntimeException("Legal document not found with id: " + documentId));

        // 创建法律法规文件目录
        Path uploadPath = Paths.get(uploadDir + "/legal-docs/" + documentId);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        Path filePath = uploadPath.resolve(fileName);

        // 保存文件
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

        // 更新文件路径
        document.setDocumentPath("legal-docs/" + documentId + "/" + fileName);
        legalDocumentRepository.save(document);

        return "legal-docs/" + documentId + "/" + fileName;
    }
}